﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;

namespace ProductSystem.BLL.Common
{
    public static class DataTableHelper
    {
        /// <summary>
        /// 将DataTable转换为实体类集合
        /// </summary>
        /// <typeparam name="T">实体类</typeparam>
        /// <param name="dt">DataTable</param>
        /// <returns>实体类集合</returns>
        public static List<T> GetList<T>(this DataTable dt) where T : class, new()
        {
            List<T> list = new List<T>();
            PropertyInfo[] properties = typeof(T).GetProperties().Where(t => dt.Columns.Contains(t.Name)).ToArray();
            foreach (DataRow dr in dt.Rows)
            {
                T data = new T();
                foreach (PropertyInfo property in properties)
                {
                    if (!Convert.IsDBNull(dr[property.Name]))
                    {
                        property.SetValue(data, dr[property.Name], null);
                    }
                }
                list.Add(data);
            }
            return list;
        }

        /// <summary>
        /// 将实体类集合转换为DataTable
        /// </summary>
        /// <typeparam name="T">实体类</typeparam>
        /// <param name="list">实体类集合</param>
        /// <returns>DataTable</returns>
        public static DataTable GetDataTable<T>(this List<T> list)
        {
            DataTable dt = new DataTable();
            PropertyInfo[] properties = typeof(T).GetProperties();
            Type propertyType;
            foreach (PropertyInfo property in properties)
            {
                propertyType = property.PropertyType;
                if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
                {
                    dt.Columns.Add(property.Name, Nullable.GetUnderlyingType(propertyType));
                }
                else
                {
                    dt.Columns.Add(property.Name, propertyType);
                }
            }
            foreach (T data in list)
            {
                DataRow dr = dt.NewRow();
                foreach (PropertyInfo property in properties)
                {
                    dr[property.Name] = property.GetValue(data, null) ?? DBNull.Value;
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }
    }
}
